
package com.sound.controller;

import com.google.common.collect.Lists;
import com.sound.common.ParamCode;
import com.sound.common.Response;
import com.sound.model.TypeModel;
import com.sound.model.UserTypeModel;
import com.sound.service.TypeService;
import com.sound.vo.UserTypeVo;

import io.swagger.annotations.Api;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

/**
 * Created by Administrator on 2018/5/7.
 */
@RestController
@Api(tags = "用户收藏类型")
@RequestMapping(path="/userType")
public class UserTypeController extends BaseController<UserTypeModel>{

	private static final Logger logger = LoggerFactory.getLogger(UserTypeController.class);


	@Autowired
	private TypeService typeService;


    @GetMapping(path = "findById")
    @Override
    public Response<UserTypeModel> findById(@RequestParam("id")Long id) {
        return super.findById(id);
    }

    @GetMapping(path = "save")
    public Response<UserTypeModel> save(@Valid UserTypeModel userTypeModel, BindingResult result) {
        return super.save(userTypeModel, result);
    }


    @GetMapping(path = "deleteById")
    public Response<Void> deleteById(@RequestParam("id") Long id) {
        return super.deleteById(id);
    }
    
    
	@GetMapping("/findAll")
	public Response<UserTypeVo> findAllType(@RequestParam("userId") String userId) {
		UserTypeModel userTypeModel = new UserTypeModel();
		userTypeModel.setUserId(userId);
		Response<Iterable<UserTypeModel>> tmpResp = super.findAll(userTypeModel);
		Response<UserTypeVo> resp   = new Response<UserTypeVo>(true);
		Iterator<UserTypeModel> userTypeIterator =  tmpResp.getData().iterator();
		UserTypeVo utv = new UserTypeVo();
		try{
			if(userTypeIterator.hasNext()) {
				UserTypeModel utm = userTypeIterator.next();
				utv.setUserTypeModel(utm);
				String[] typeIds = utm.getTypeIds().split(",");
				List<Long> typeIdL = stringToLong(typeIds);
				Iterable<TypeModel> typeModels =  typeService.findAllById(typeIdL);
				utv.setTypeModels(typeModels);
			}else {
				Iterable<TypeModel> typeModels = typeService.findAll();

				List<TypeModel> list = Lists.newArrayList(typeModels);
				if(list.size()>7){
					int index = (int) (Math.random()*(list.size() - 7)) ;
					list = list.subList(index, index+7);
				}
				utv.setTypeModels(list);
			}

			resp.setData(utv);
			return resp;
		}catch (Exception e){
			logger.error("findAll fail:",e);
		}
		resp.setRespone(ParamCode.FAIL);
		return resp;
	}
	
	private static List<Long> stringToLong(String[]ids) {
		List<Long> idLongs = new ArrayList<Long>();
		for(String id : ids) {
			idLongs.add(Long.valueOf(id));
		}
		return idLongs;
	}
}

